package com.leetcode.algorithm.y22.m09.w2;

/**
 * 1592. 重新排列单词间的空格
 * 
 * https://leetcode.cn/problems/rearrange-spaces-between-words/
 * 
 * @author jie.deng
 *
 */
class Question1592Solution01 {

	public String reorderSpaces(String text) {
		int spaceCnt = 0;
		int wordCnt = 0;
		int idx = 0;
		int len = text.length();
		while (idx < len) {
			if (' ' == text.charAt(idx)) {
				spaceCnt++;
				idx++;
			} else {
				wordCnt++;
				do {
					idx++;
				} while (idx < len && ' ' != text.charAt(idx));
			}
		}
		if (spaceCnt == 0 || wordCnt == 0) {
			return text;
		}
		int gap = wordCnt == 1 ? 0 : spaceCnt / (wordCnt - 1);
		StringBuilder builder = new StringBuilder(len);
		idx = 0;
		while (idx < len && ' ' == text.charAt(idx)) {
			idx++;
		}
		while (idx < len) {
			if (' ' != text.charAt(idx)) {
				builder.append(text.charAt(idx));
				idx++;
			} else {
				for (int i = 0; i < gap; i++) {
					builder.append(' ');
				}
				do {
					idx++;
				} while (idx < len && ' ' == text.charAt(idx));
			}
		}
		while (builder.length() < len) {
			builder.append(' ');
		}
		return builder.toString().substring(0, len);
	}

}